import os
import uuid
import requests
import time
import random
from create_spec import create_spec
from create import create
from store_image import store_image

BASE_URL = 'https://open.feishu.cn'
APP_ID = 'cli_a89f1ee951f9d00e'
APP_SECRET = 'MfMtAGE2IYX4N6DjvzsPIgC3ZhkSvjgs'
headers = {
    'Content-Type': 'application/json',
}

token_expire_time = 0

def get_access_token():
    """获取访问令牌"""
    global token_expire_time
    if token_expire_time != 0 and token_expire_time - time.time() > 10:
        # print(f"令牌有校, 跳过令牌刷新, token_expire_time = {int(token_expire_time)}, current_time = {int(token_expire_time)}")
        return

    url = f'{BASE_URL}/open-apis/auth/v3/tenant_access_token/internal'
    data = {
        'app_id': APP_ID,
        'app_secret': APP_SECRET
    }
    print('POST', url)
    response = requests.post(url, json=data)
    if response.status_code == 200 and response.json().get('code') == 0:
        expire = response.json().get('expire')
        token_expire_time = expire + time.time()
        # print(f"获取访问令牌成功: expire = {response.json().get('expire')}s")
        access_token = response.json().get('tenant_access_token')
        if access_token:
            headers['Authorization'] = f'Bearer {access_token}'
        else:
            print("get_access_token failed")
            raise SystemExit('获取访问令牌失败')
    else:
        print(f"获取访问令牌失败: {response.status_code}, {response.text}")
        return None

def build_table_url(endpoint, app_token, table_id):
    """构建表格URL"""
    """构建API URL"""
    return f'{BASE_URL}/open-apis/bitable/v1/apps/{app_token}/tables/{table_id}/{endpoint}'

def download_image(url, dir_name='images'):
    get_access_token()

    print('GET', url)
    response = requests.get(url, headers={'Authorization': headers["Authorization"]})
    if response.status_code == 200:
        # 生成本地文件名
        file_name = f"{uuid.uuid4().hex}.jpg"
        file_path = f'{dir_name}/{file_name}'  # 保存到images目录下
        
        # 确保images目录存在
        os.makedirs(dir_name, exist_ok=True)
        
        # 保存图片到本地
        with open(file_path, 'wb') as f:
            f.write(response.content)
        
        print(f"图片下载成功并保存到: {file_path}")
        return file_path
    else:
        print(f"图片下载失败, 状态码: {response.status_code}")
        return None


def upload_media(file_path, app_token):
    get_access_token()

    if file_path is None:
        raise ValueError("文件路径无效")
    
    if file_path.startswith('http'):
        # 保存至本地
        file_path = download_image(file_path)
        if file_path is None:
            raise ValueError("保存图片失败")

    if not os.path.exists(file_path):
        raise ValueError(f"文件不存在: {file_path}")

    """上传素材"""
    file_size = os.path.getsize(file_path)
    file_name = os.path.basename(file_path)

    url = f'{BASE_URL}/open-apis/drive/v1/medias/upload_all'

    upload_headers = headers.copy()
    upload_headers.pop('Content-Type', None)

    files = {
        'file_name': (None, file_name),
        'parent_type': (None, 'bitable_image'),
        'parent_node': (None, app_token),
        'size': (None, str(file_size)),
        'file': (open(file_path, 'rb')),
    }

    print('POST', url)
    response = requests.post(url, headers=upload_headers, files=files)
    if response.status_code == 200:
        # print(f"upload_all_url 请求成功, response = {response.json()}")
        response_data = response.json()
        if response_data.get('code') == 0:
            file_token = response_data.get('data', {}).get('file_token')
            print(f"成功上传素材, file_token = {file_token}")
            return file_token
        else:
            print(f"上传失败, 错误信息: {response_data.get('error')}")
            raise SystemExit('上传素材失败')
    else:
        print(f"upload_all_url 请求失败, response = {response.json()}")
        raise SystemExit('上传素材失败')

def batch_create_records(records, app_token, table_id):
    get_access_token()

    """新增多条记录"""
    '''
    {
        "records": [
            {
                "fields": {
                    "文本": "文本内容",
                    "条码": "qawqe",
                    "数字": 100,
                    "货币": 3,
                    "评分": 3,
                    "进度": 0.25,
                    "单选": "选项1",
                    "多选": [
                        "选项1",
                        "选项2"
                    ],
                    "日期": 1674206443000,
                    "复选框": true,
                    "人员": [
                        {
                            "id": "ou_2910013f1e6456f16a0ce75ede950a0a"
                        },
                        {
                            "id": "ou_e04138c9633dd0d2ea166d79f548ab5d"
                        }
                    ],
                    "群组": [
                        {
                            "id": "oc_cd07f55f14d6f4a4f1b51504e7e97f48"
                        }
                    ],
                    "电话号码": "13026162666",
                    "超链接": {
                        "text": "飞书多维表格官网",
                        "link": "https://www.feishu.cn/product/base"
                    },
                    "附件": [
                        {
                            "file_token": "Vl3FbVkvnowlgpxpqsAbBrtFcrd"
                        }
                    ],
                    "单向关联": [
                        "recHTLvO7x",
                        "recbS8zb2m"
                    ],
                    "双向关联": [
                        "recHTLvO7x",
                        "recbS8zb2m"
                    ],
                    "地理位置": "116.397755,39.903179"
                }
            },
            {
                "fields": {
                    "文本": "文本内容2"
                }
            }
        ]
    }
    '''
    url = build_table_url('records/batch_create', app_token, table_id)
    data = {"records": records}

    print('POST', url)
    response = requests.post(url, headers=headers, json=data)
    if response.status_code == 200:
        # print(f"batch_create_records_url 请求成功, response = {response.json()}")
        response_data = response.json()
        if response_data.get('code') == 0:
            print(f"成功新增 {len(records)} 条记录")
            return True
        else:
            print(f"新增失败, 错误信息: {response_data.get('error')}")
            return False
    else:
        print(f"batch_create_records_url 请求失败, response = {response.json()}")
        raise SystemExit('新增在线表格失败')